package com.mouliu.base.syn08;

import java.util.ArrayList;
import java.util.List;

/**
 * volatile 具有可见性
 * @author liu.mou
 */
public class ListAdd1 {
    private volatile static List list = new ArrayList();

    public void add(){
        list.add("bjsxt");
    }
    public int size(){
        return list.size();
    }

    public static void main(String[] args){
        final ListAdd1 list1 = new ListAdd1();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i=0;i<10;i++){
                        list1.add();
                        System.out.println("当前线程：" + Thread.currentThread().getName() + "添加了一个元素..");
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t2");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    if (list1.size()==5){
                        System.out.println("当前线程收到通知：" + Thread.currentThread().getName() + " list size = 5 线程停止..");
                        throw new RuntimeException();
                    }
                }
            }
        },"t1");
        t1.start();
        t2.start();
    }
}
/**
 *理解:1线程一开始执行，打印对应的数据，然后休眠1秒，这时候线程儿开始执行，一直循环判断size是否等于5,当等于5的时候在抛出异常。
 * **/
